package per.dj.testpro.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.List;

public class CommonUtils {

    public static String readContentFromPost(String POST_URL,String content) throws IOException {
        URL postUrl = new URL(POST_URL);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        //        connection.setRequestProperty("Content-Type",
        //                "application/x-www-form-urlencoded");
        connection.setRequestProperty("contentType", "utf-8");
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        //        out.writeBytes(content);
        out.write(content.getBytes("utf-8"));
        out.flush();
        out.close(); // flush and close
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream(),"utf-8"));
        String line="";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            return line;
        }

        reader.close();
        connection.disconnect();

        return line;
    }

    /**
     * @param date
     * @param string
     * @return
     */
    public static String getTimeFormat(Date date, String string) {
        SimpleDateFormat sdFormat;
        if (isEmptyString(string)) {
            sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            sdFormat = new SimpleDateFormat(string);
        }
        try {
            return sdFormat.format(date);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 判断String是否为空
     *
     */
    public static boolean isEmptyString(String value) {
        if (value == null || value.length() == 0) {
            return true;
        }
        return false;
    }

    public static List<String> spritString(String str){
        List<String> result = new ArrayList<String>();
        int iPos = 0;
        int iLen = str.length();
        while(iLen>=2){
            String tmp = str.substring(0, 2);
            result.add(tmp);
            str = str.substring(2);
            iLen = str.length();
        }
       return result;
    }

}
